<?php


namespace Tools\Utils;


use think\helper\Str;

class Strings
{

    /**
     * 文字截取
     * @param $content
     * @param $strlen
     * @return mixed|string
     */
    public static function cutString($content, $strlen)
    {
        $contents = self::replacehtmlchar($content);
        if (mb_strlen($contents) > $strlen) {
            $contents = mb_substr($contents, 0, $strlen, 'utf-8');
        }

        return $contents;
    }

    /**
     * 替换html标签
     * @param $content
     * @return mixed
     */
    public static function replacehtmlchar($content)
    {
        $search = [
            "'<script[^>]*?>.*?</script\s*?>'si", // 去掉 javascript
            "'<style[^>]*?>.*?</style\s*?>'si", // 去掉 css
            "'<[/!]*?[^<>]*?>'si", // 去掉 HTML 标记
            "'<!--[/!]*?[^<>]*?>'si", // 去掉 注释标记
            "'([rn])[s]+'", // 去掉空白字符
            "'&(quot#34);'i", // 替换 HTML 实体
            "'&(amp#38);'i",
            "'&(lt#60);'i",
            "'&(gt#62);'i",
            "'&(nbsp#160);'i",
            "'&(iexcl#161);'i",
            "'&(cent#162);'i",
            "'&(pound#163);'i",
            "'&(copy#169);'i",
//            "'&#(d+);'e",
        ]; // 作为 PHP 代码运行
        $replace = [
            "",
            "",
            "",
            "",
            "\1",
            "\"",
            "&",
            "<",
            ">",
            " ",
            chr(161),
            chr(162),
            chr(163),
            chr(169),
//            "chr(\1)",
        ];
//        $contents = preg_replace($search, $replace, $content);
        $contents = preg_replace_callback($search, function ($match) use ($replace) {
            foreach ($replace as $k => $v) {
                return str_replace($match[0], $v, $match[0]);
            }
        }, $content);
        $contents = str_replace('&nbsp;', ' ', $contents);
        $contents = str_replace(' ', '', $contents);
        return $contents;
    }

    //文章内容获取HTML内容
    public static function getHtmlString($content)
    {
        return htmlspecialchars_decode($content);

        $content = preg_replace("#<script[^>]*?>.*?</script\s*?>#is", "", $content);

        return htmlspecialchars_decode(html_entity_decode(stripcslashes($content), ENT_COMPAT, 'UTF-8'));
    }

    /**
     *过滤脏字
     */
    public static function filter_dirty($string)
    {
        \Lib\DirtyFilter\DirtyFilter::getInstance()->replace_dirty($string, $string);

        return $string;
    }

    /**
     * 数据脱敏
     * @param $string 需要脱敏值
     * @param int $start 开始
     * @param int $length 结束
     * @param string $re 脱敏替代符号
     * @return bool|string
     * 例子:
     * dataDesensitization('18811113683', 3, 4); //188****3683
     * dataDesensitization('乐杨俊', 0, -1); //**俊
     */
    public static function dataDesensitization($string, $start = 0, $length = 0, $re = '*')
    {
        if (empty($string)) {
            return false;
        }
        $strarr = array();
        $mb_strlen = mb_strlen($string, 'utf8');
        while ($mb_strlen) {//循环把字符串变为数组
            $strarr[] = mb_substr($string, 0, 1, 'utf8');
            $string = mb_substr($string, 1, $mb_strlen, 'utf8');

            $mb_strlen = mb_strlen($string, 'utf8');
        }
        $strlen = count($strarr);
        $begin = $start >= 0 ? $start : ($strlen - abs($start));
        $end = $last = $strlen - 1;
        if ($length > 0) {
            $end = $begin + $length - 1;
        } elseif ($length < 0) {
            $end -= abs($length);
        }
        for ($i = $begin; $i <= $end; $i++) {
            $strarr[$i] = $re;
        }
        if ($begin > $end || $begin > $last || $end > $last) return '';
        return implode('', $strarr);
    }


    /**
     * 敏感词过滤
     *
     * @param string
     * @return string
     */
    public static function sensitive_words_filter($str)
    {
        if (!$str) return '';
        $file = app()->getAppPath() . 'public/statics/plug/censorwords/CensorWords';
        $words = file($file);
        foreach ($words as $word) {
            $word = str_replace(array("\r\n", "\r", "\n", "/", "<", ">", "=", " "), '', $word);
            if (!$word) continue;

            $ret = preg_match("/$word/", $str, $match);
            if ($ret) {
                return $match[0];
            }
        }
        return '';
    }


    public static function strexists($string, $find)
    {
        return !(strpos($string, $find) === FALSE);
    }

    /** TODO 系统未使用
     * @param string $string 需要替换的字符串
     * @param int $start 开始的保留几位
     * @param int $end 最后保留几位
     * @return string
     */
    public static function str_middle_replace($string, $start, $end)
    {
        $strlen = mb_strlen($string, 'UTF-8');//获取字符串长度
        $firstStr = mb_substr($string, 0, $start, 'UTF-8');//获取第一位
        $lastStr = mb_substr($string, -1, $end, 'UTF-8');//获取最后一位
        return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($string, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;

    }

    // 过滤掉emoji表情
    public static function filter_emoji($str)
    {
        $str = preg_replace_callback(    //执行一个正则表达式搜索并且使用一个回调进行替换
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);
        return $str;
    }

    /**
     * 生成14位的随机码（不带前缀的情况下），生成的随机码由数字、大小字母组成（区分大小写）
     *
     * @param string $pre 前缀
     *
     * @return string
     */
    function createNo($pre = '')
    {
        if (!$pre) {
            $pre = mt_rand(0, 9);
        }
        mt_srand(( double )microtime() * 1000000);
        $tms = explode(' ', date('Y m d G i s'));

        /* PHPALLY + 年月日时分秒 + 3位随机数 */

        return $pre . $tms[0] . $tms[1] . $tms[2] . num2char($tms[3]) . num2char($tms[4]) . num2char($tms[5]) . str_pad(mt_rand(1, 999), 3, '0', STR_PAD_LEFT);
    }

    /**
     * 将小于62的非负整数转为单个字符
     */
    function num2char($num)
    {
        $num = (int)$num;
        if ($num > 61 || $num < 10) {
            return $num;
        }
        if ($num < 36) {
            return chr(0x41 + $num - 0xA);
        }

        return chr(0x61 + $num - 0x24);
    }

    /**
     * 字符串转换成数组
     *
     * @time 2019年12月25日
     * @param string $string
     * @param string $dep
     * @return array
     */
    public static function stringToArrayBy(string $string, $dep = ','): array
    {
        if (Str::contains($string, $dep)) {
            return explode($dep, trim($string, $dep));
        }

        return [$string];
    }

    /**
     * 过滤空字符字段
     *
     * @time 2021年01月16日
     * @param $data
     * @return mixed
     */
    public static function filterEmptyValue($data)
    {
        foreach ($data as $k => $v) {
            if (!$v) {
                unset($data[$k]);
            }
        }

        return $data;
    }

}
